<template>
  <div style="min-width:1050px;" v-loading="getLoading">
    <div class="detail-info">
      <p class="detail-title">
        <span>兑换汇率</span>
        <el-button v-if="!exchangeEdit" type="text" @click="onExchangeEdit">编辑</el-button>
      </p>
      <el-form ref="exchangeForm">
        <el-form-item label="">
          <span>1 智币 = <el-input-number :disabled="!exchangeEdit"
            :max="99999"
            :precision="2"
            :min="0.01"
            :controls="false"
            class="pay-amount-input"
            v-model="exchangeRate"></el-input-number> 人民币</span>
        </el-form-item>
      </el-form>
      <div v-show="exchangeEdit">
        <el-button size="small" type="primary" :loading="payEditLoading" @click="onExchangeSave">保存</el-button>
        <el-button size="small" @click="onExchangeReset">取消</el-button>
      </div>
    </div>
    <div class="detail-info">
      <div class="detail-title">
        <span>充值金额</span>
        <el-button v-if="!payAmountEdit" type="text" @click="onPayAmountEdit">编辑</el-button>
      </div>
       <el-form :model="payAmountForm" ref="payAmountForm" label-width="140px" size="small">
        <el-form-item label="默认快捷充值金额：" prop="quick_pay_amount_opt" :rules="rules.quick_pay_amount_opt">
          <div>
            <el-input-number
              v-for="(item,index) in payAmountForm.quick_pay_amount_opt"
              :key="index"
              :disabled="!payAmountEdit"
              :min="1"
              :max="99999"
              :precision="2"
              :controls="false"
              class="pay-amount-input"
              v-model="payAmountForm.quick_pay_amount_opt[index]"/>
              <el-button v-show="payAmountEdit" :disabled="payAmountForm.quick_pay_amount_opt.length<4" @click="onDelQuickPay" style="margin-left:25px">
                <i class="el-icon-minus"></i>
              </el-button>
              <el-button  v-show="payAmountEdit" :disabled="payAmountForm.quick_pay_amount_opt.length>4" @click="onAddQuickPay"><i class="el-icon-plus"></i></el-button>
          </div>
        </el-form-item>
        <el-form-item label="允许金额自定义：">
          <el-switch
            :disabled="!payAmountEdit"
            :active-value="1"
            :inactive-value="0"
            v-model="payAmountForm.enable_custom_pay_amount">
          </el-switch>
        </el-form-item>
        <el-form-item label="最低充值金额：" v-if="payAmountForm.enable_custom_pay_amount">
          <el-input-number :disabled="!payAmountEdit"
            :max="99999"
            :min="1"
            :precision="2"
            :controls="false"
            class="pay-amount-input"
            v-model="payAmountForm.least_pay_amount"></el-input-number>
        </el-form-item>
      </el-form>
      <div v-show="payAmountEdit">
        <el-button size="small" type="primary" :loading="payEditLoading" @click="onPayAmountSave">保存</el-button>
        <el-button size="small" @click="onPayAmountReset">取消</el-button>
      </div>
    </div>
    <div class="detail-info">
      <p class="detail-title">
        <span>充值优惠</span>
        <el-button v-if="!discountEdit" type="text" @click="onDiscountEdit">编辑</el-button>
      </p>
      <el-form :model="discountForm" ref="discountForm" size="small">
        <el-form-item label="充值优惠方式：" class="discount-type">
          <el-checkbox :disabled="!discountEdit" v-model="discountForm.enable_pay_discount_rate" :true-label="1" :false-label="0" label="付款折扣"></el-checkbox>
          <el-checkbox :disabled="!discountEdit" v-model="discountForm.enable_pay_discount_give" :true-label="1" :false-label="0" label="赠币智币"></el-checkbox>
        </el-form-item>
        <div class="discount-content">
          <div>
            <div class="discount-title">
              <span>充值金额（￥）：</span>
              <span>付款折扣（%）：</span>
            </div>
            <el-form-item v-for="(item,index) in discountForm.pay_discount_rate_opt" :key="index" :prop="'pay_discount_rate_opt.' + index" :rules="rules.payDiscountOpt">
              <el-input-number
                :controls="false"
                :min="0"
                :max="99999"
                :precision="2"
                :disabled="!discountEdit"
                class="pay-amount-input"
                v-model="discountForm.pay_discount_rate_opt[index].start"></el-input-number>
                <span style="margin-left:15px">~</span>
              <el-input-number
                :controls="false"
                :min="0"
                :max="99999"
                :precision="2"
                :disabled="!discountEdit"
                class="pay-amount-input"
                v-model="discountForm.pay_discount_rate_opt[index].stop"></el-input-number>
              <el-input-number
                :controls="false"
                :min="1"
                :max="100"
                :precision="0"
                :disabled="!discountEdit"
                style="margin-left:40px"
                class="pay-amount-input"
                v-model="discountForm.pay_discount_rate_opt[index].discount"></el-input-number>
                <el-button v-show="discountEdit" :disabled="discountForm.pay_discount_rate_opt.length<2" @click="onDelDiscount('pay_discount_rate_opt',index)" style="margin-left:25px">
                  <i class="el-icon-minus"></i>
                </el-button>
            </el-form-item>
            <el-button
              v-show="discountEdit"
              :disabled=" discountForm.pay_discount_rate_opt.length>9"
              size="small"
              class="discount-add-btn"
              @click="onAddDiscount('pay_discount_rate_opt')">
              <i class="el-icon-plus"></i>
            </el-button>
          </div>
          <div class="discount-content-right">
            <div class="discount-title">
              <span>充值金额（￥）：</span>
              <span>赠送（智币）：</span>
            </div>
            <el-form-item v-for="(item,index) in discountForm.pay_discount_give_opt" :key="index" :prop="'pay_discount_give_opt.' + index" :rules="rules.payDiscountOpt">
              <el-input-number
                :controls="false"
                :max="99999"
                :precision="2"
                :disabled="!discountEdit"
                class="pay-amount-input"
                v-model="discountForm.pay_discount_give_opt[index].start"></el-input-number>
                <span style="margin-left:15px">~</span>
              <el-input-number
                :controls="false"
                :min="0"
                :max="99999"
                :precision="2"
                :disabled="!discountEdit"
                class="pay-amount-input"
                v-model="discountForm.pay_discount_give_opt[index].stop"></el-input-number>
              <el-input-number
                :controls="false"
                :min="0"
                :max="100000"
                :precision="0"
                :disabled="!discountEdit"
                style="margin-left:40px"
                class="pay-amount-input"
                v-model="discountForm.pay_discount_give_opt[index].discount"></el-input-number>
                <el-button v-show="discountEdit" :disabled="discountForm.pay_discount_give_opt.length<2" @click="onDelDiscount('pay_discount_give_opt',index)" style="margin-left:25px">
                  <i class="el-icon-minus"></i>
                </el-button>
            </el-form-item>
            <el-button v-show="discountEdit"
              :disabled=" discountForm.pay_discount_give_opt.length>9"
              size="small"
              class="discount-add-btn"
              @click="onAddDiscount('pay_discount_give_opt')"><i class="el-icon-plus"></i></el-button>
          </div>
        </div>
      </el-form>
       <div v-show="discountEdit" class="discount-edit-btn">
        <el-button size="small" type="primary" :loading="discountEditLoding" @click="onDiscountSave">保存</el-button>
        <el-button size="small" @click="onDiscountReset">取消</el-button>
      </div>
    </div>
    <div class="detail-info">
      <div class="detail-title">
        <span>用户赠币</span>
        <el-button v-if="!payGiftEdit" type="text" @click="onGiftEdit">编辑</el-button>
      </div>
      <el-form :model="giftForm" ref="giftForm" size="small" label-width="140px">
        <el-form-item label="开启赠送：">
          <el-switch
            :disabled="!payGiftEdit"
            v-model="giftForm.enable_gift">
          </el-switch>
        </el-form-item>
        <el-form-item label="赠送金额（智币）：" v-if="payAmountForm.enable_custom_pay_amount">
          <el-input-number :disabled="!payGiftEdit"
            :max="99999"
            :precision="0"
            :min="1"
            :controls="false"
            class="pay-amount-input"
            v-model="giftForm.gift_num"></el-input-number>
        </el-form-item>
      </el-form>
      <div v-show="payGiftEdit">
        <el-button size="small" type="primary" :loading="giftEditLoding" @click="onGiftSave">保存</el-button>
        <el-button size="small" @click="onGiftReset">取消</el-button>
      </div>
    </div>
  </div>
</template>
<script>
import { formatMoney } from '@/utils'
import { productList, addMenu, updateMenu } from '@/api/member/product'
import { getSettingList, setPaySetting } from '@/api/recharge-zb'
export default {
  name: 'RechargeZb',
  data () {
    const validateDiscountRate = (rule, value, callback) => {
      if (!value.start || !value.stop || !value.discount) {
        callback(new Error('充值金额或赠送不能为空'))
      } else if (value.start > value.stop) {
        callback(new Error('请输入正确的范围值'))
      } else {
        const field = rule.field.split('.')
        const type = field[0]
        const index = parseInt(field[1])
        const flag = this.discountForm[type].some((item, index1) => {
          return index1 !== index && ((value.start >= item.start && value.start <= item.stop) || (value.stop >= item.start && value.stop <= item.stop))
        })
        if (flag) {
          callback(new Error('区间交错'))
        } else {
          callback()
        }
      }
    }
    return {
      getLoading: true,
      exchangeEdit: false,
      payAmountEdit: false,
      payEditLoading: false,
      discountEdit: false,
      discountEditLoding: false,
      payGiftEdit: false,
      giftEditLoding: false,
      exchangeRate: undefined,
      payAmountForm: {
        quick_pay_amount_opt: []
      },
      discountForm: {
        enable_pay_discount_rate: 0,
        enable_pay_discount_give: 0,
        pay_discount_rate_opt: [],
        pay_discount_give_opt: []
      },
      giftForm: {
        enable_gift: false,
        gift_num: 0
      },
      rules: {
        quick_pay_amount_opt: [
          {
            type: 'array',
            defaultField: {
              required: true,
              type: 'number',
              message: '默认快捷充值金额不能为空'
            },
            trigger: 'blur'
          }
        ],
        payDiscountOpt: [
          { validator: validateDiscountRate, trigger: [] }
        ]
      }
    }
  },
  filters: {
    discountStrFilter (item) {
      const arr = []
      if (item.enable_pay_discount_rate) {
        arr.push('付款折扣')
      }
      if (item.enable_pay_discount_give) {
        arr.push('赠币智币')
      }
      return arr.join('，') || '无'
    }
  },
  created () {
    productList({
      page: 1,
      page_size: 10,
      status: 1,
      attr_type: 3
    }).then(response => {
      const list = response.data.list
      const obj = list[0] || {}
      this.exchangeRate = obj.price ? formatMoney(obj.price) : undefined
      this.exchangeRateId = obj.id
    })
    getSettingList({ key: ['exchange_rate', 'pay_amount', 'pay_discount', 'gift_virtual_coin'] }).then(res => {
      const data = res.data.data || {}
      // const exchangeRate = data.exchange_rate || {}
      // this.exchangeRate = exchangeRate.num / exchangeRate.unit_price * 100
      this.formatPayInfo(data.pay_amount)
      this.formatDiscountInfo(data.pay_discount)
      if (data.gift_virtual_coin) {
        this.giftForm.enable_gift = data.gift_virtual_coin.enable_gift
        this.giftForm.gift_num = data.gift_virtual_coin.gift_num
      }
    }).finally(() => {
      this.getLoading = false
    })
  },
  methods: {
    formatPayInfo (obj = {}) {
      this.payAmountForm = {
        quick_pay_amount_opt: (obj.quick_pay_amount_opt || []).map(item => formatMoney(item)),
        enable_custom_pay_amount: obj.enable_custom_pay_amount || 0,
        least_pay_amount: formatMoney(obj.least_pay_amount)
      }
    },
    formatDiscountInfo (obj = {}) {
      this.discountForm = {
        enable_pay_discount_rate: obj.enable_pay_discount_rate || 0,
        enable_pay_discount_give: obj.enable_pay_discount_give || 0,
        pay_discount_rate_opt: this.formatDiscountMoney(obj.pay_discount_rate_opt),
        pay_discount_give_opt: this.formatDiscountMoney(obj.pay_discount_give_opt)
      }
    },
    formatDiscountMoney (list = []) {
      list.map(item => {
        item.start = formatMoney(item.start)
        item.stop = formatMoney(item.stop)
        return item
      })
      return list
    },
    /** ********** 兑换汇率模块 ****************/
    onExchangeEdit () {
      this.exchangeRateOld = this.exchangeRate
      this.exchangeEdit = true
    },
    onExchangeSave () {
      if (!this.exchangeRate) return
      let submitFn = addMenu
      const params = {
        status: 1,
        attr_type: 3,
        name: '智币',
        price: Math.round(this.exchangeRate * 100)
      }
      if (this.exchangeRateId) {
        submitFn = updateMenu
        params.id = this.exchangeRateId
      }
      submitFn(params).then(response => {
        this.msgSuccess('修改成功')
        this.exchangeEdit = false
      })
    },
    onExchangeReset () {
      this.$refs.exchangeForm.clearValidate()
      this.exchangeRate = this.exchangeRateOld
      this.exchangeEdit = false
    },
    /** ********** 充值金额模块 ****************/
    onPayAmountEdit () {
      this.payAmountOld = JSON.parse(JSON.stringify(this.payAmountForm))
      this.payAmountEdit = true
    },
    onDelQuickPay () {
      this.payAmountForm.quick_pay_amount_opt.pop()
    },
    onAddQuickPay () {
      this.payAmountForm.quick_pay_amount_opt.push(undefined)
    },
    onPayAmountSave () {
      this.$refs.payAmountForm.validate((valid) => {
        if (valid) {
          const params = {
            quick_pay_amount_opt: (this.payAmountForm.quick_pay_amount_opt || []).map(item => Math.round(item * 100)),
            enable_custom_pay_amount: this.payAmountForm.enable_custom_pay_amount,
            least_pay_amount: Math.round(this.payAmountForm.least_pay_amount * 100)
          }
          this.payEditLoading = true
          setPaySetting({ key: 'pay_amount', value: params }).then(() => {
            this.msgSuccess('保存成功')
            this.payAmountEdit = false
          }).finally(() => {
            this.payEditLoading = false
          })
        }
      })
    },
    onPayAmountReset () {
      this.$refs.payAmountForm.clearValidate()
      this.payAmountForm = this.payAmountOld
      this.payAmountEdit = false
    },
    /** ********** 充值优惠模块 ****************/
    onDiscountEdit () {
      this.discountFormOld = JSON.parse(JSON.stringify(this.discountForm))
      this.discountEdit = true
    },
    onAddDiscount (type) {
      this.discountForm[type].push({ 'start': undefined, 'stop': undefined, 'discount': undefined })
    },
    onDelDiscount (type, index) {
      this.discountForm[type].splice(index, 1)
    },
    onDiscountSave () {
      this.$refs.discountForm.validate((valid) => {
        if (valid) {
          const params = JSON.parse(JSON.stringify(this.discountForm))
          params.pay_discount_rate_opt = this.formatPrice(params.pay_discount_rate_opt)
          params.pay_discount_give_opt = this.formatPrice(params.pay_discount_give_opt)
          this.discountEditLoding = true
          setPaySetting({ key: 'pay_discount', value: params }).then(() => {
            this.msgSuccess('保存成功')
            this.discountEdit = false
          }).finally(() => {
            this.discountEditLoding = false
          })
        }
      })
    },
    formatPrice (list = []) {
      list.map(item => {
        item.start = Math.round(item.start * 100)
        item.stop = Math.round(item.stop * 100)
        return item
      })
      return list
    },
    onDiscountReset () {
      this.$refs.discountForm.clearValidate()
      this.discountForm = this.discountFormOld
      this.discountEdit = false
    },
    /** ********** 赠送模块 ****************/
    onGiftEdit () {
      this.giftFormOld = JSON.parse(JSON.stringify(this.giftForm))
      this.payGiftEdit = true
    },
    onGiftSave () {
      const params = this.giftForm
      this.giftEditLoding = true
      setPaySetting({ key: 'gift_virtual_coin', value: params }).then(() => {
        this.msgSuccess('保存成功')
        this.payGiftEdit = false
      }).finally(() => {
        this.giftEditLoding = false
      })
    },
    onGiftReset () {
      this.giftForm = this.giftFormOld
      this.payGiftEdit = false
    }
  }
}
</script>
<style lang="scss" scoped>
.detail-info{
  margin-bottom: 20px;
  &:last-child{
    margin-bottom: 0;
  }
}
.detail-title{
  margin-bottom: 16px;
  font-size: 16px;
  font-weight: bold;
  .el-button{
    margin-left: 20px;
    padding: 0;
  }
}
.pay-amount-input{
  width: 120px;
  margin-left: 15px;
  &:first-child{
     margin-left: 0;
  }
}
.discount-content{
  display: flex;
  >div{
    width: 525px;
  }
  .discount-content-right{
    margin-left: 30px;
  }
}
.discount-title{
  margin-bottom: 15px;
  color: #999;
  span:last-child{
    margin-left: 210px;
  }
}
.discount-add-btn{
  width: 510px;
}
.discount-edit-btn{
  margin-left: 15px;
  margin-top: 20px;
}
</style>
<style lang="scss">
.pay-amount-input{
  .is-disabled .el-input__inner{
    color: #333;
  }
}
.discount-type .el-checkbox__input.is-disabled.is-checked .el-checkbox__inner{
  background-color: #409EFF;
}
</style>
